/*
{
"状态":1,
"名称":"同步-钉钉用户",
"作者":"马学兵",
"创建时间":"2018-08-28",
"功能":"新增-钉钉用户",
"log": [
	{"date":"" , "dev" :"" , "content" : ""}
]
}
*/
declare @platform int , @user_id varchar(1000) , @mobile varchar(100) , @name varchar(100) , @deptid varchar(100) ,@avatar varchar(2000) 
set @platform = '{platform}'
set @user_id = '{userid}'
set  @mobile = '{mobile}'
set @name = '{name}'
set @deptid = '{deptid}'
set @avatar='{avatar}'

DECLARE @company_key INT 
SELECT @company_key=company_key FROM y_platform WHERE platform_key=@platform

if not exists ( select [platform_key] from [y_platform_user] where [platform_key] = @platform and [platform_user_id] =@user_id)
begin 
	INSERT INTO [dbo].[y_platform_user]([platform_key],[platform_user_id],[user_key],[platform_user_name],[platform_user_mobile],[create_time],[update_time],[avatar])
		 VALUES(@platform ,@user_id ,0 , @name ,@mobile , getdate() , getdate(),@avatar) 
	
	
	UPDATE  pu
	   SET [user_key] = u.user_key 
	   from  [dbo].[y_platform_user] pu
		inner join y_platform p on p.[platform_key] = pu.[platform_key]
		inner join y_user u on u.[mobilephone] = @mobile and u.company_key = p.company_key 
		where pu.[platform_key] = @platform and pu.[platform_user_id] =@user_id

end
else
begin

	UPDATE [dbo].[y_platform_user]
	   SET [platform_user_name] = @name
		  ,[platform_user_mobile] =@mobile
		  ,[update_time] = getdate() 
		  ,avatar=@avatar
		where [platform_key] = @platform and [platform_user_id] =@user_id
end

-- [y_platform_department_users]

if not exists ( select [platform_key] from [y_platform_department_users] where [platform_key] = @platform and [platform_user_id] =@user_id and department_id = @deptid)
begin 
	INSERT INTO [dbo].[y_platform_department_users]([platform_key],[platform_user_id],[department_id] , 
	 [create_time],[update_time])
		 VALUES(@platform ,@user_id ,@deptid , getdate() , getdate()) 
	

end

 
--同步更新用户表
INSERT INTO y_user(company_key,user_id,user_name,simple_code,password,mobilephone)
SELECT @company_key,A.platform_user_mobile,A.platform_user_name,dbo.f_getpy(A.platform_user_name),RIGHT(A.platform_user_mobile,4),A.platform_user_mobile FROM 
(SELECT platform_user_mobile,platform_user_name FROM y_platform_user WHERE platform_key=@platform) A LEFT JOIN dbo.y_user B ON A.platform_user_mobile=B.user_id AND B.company_key=@company_key
WHERE  B.user_key IS NULL 
 
UPDATE y_platform_user SET user_key=y_user.user_key
FROM y_platform_user INNER JOIN dbo.y_user ON platform_user_mobile=user_id  AND company_key=@company_key AND platform_key=@platform
WHERE y_platform_user.user_key=0


--加入everyone 
INSERT INTO y_role_user(user_key,role_key,create_time,update_time)
SELECT A.user_key,7,getdate(),getdate() FROM  dbo.y_user A LEFT JOIN y_role_user B ON B.user_key = A.user_key AND B.role_key=7
WHERE B.user_key IS NULL 